// src/router/index.tsx

import React, { Suspense, useEffect } from "react";
import {
  BrowserRouter as Router,
  useRoutes,
  RouteObject,
  Navigate,
  useLocation,
  Outlet,
} from "react-router-dom";
import { constantRoutes, asyncRoutes } from "./routes";
import { useAppSelector, useAppDispatch } from "@store/hooks";
import { fetchUserInfo, selectUserRoles } from "@store/modules/userSlice";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { filterAsyncRoutes, generateMenu } from "@utils/auth";
import { selectUserToken } from '@store/modules/userSlice'
import { Spin } from "antd";

/**
 * 创建一个包裹 Suspense 的路由组件，统一处理 lazy 加载时的 Loading
 */
const SuspenseWrapper: React.FC<{}> = ({ children }) => (
  <Suspense fallback={<Spin size="large" className="global-loading" />}>
    {children}
  </Suspense>
);

/**
 * 合并路由并渲染。这里根据用户角色动态过滤 asyncRoutes。
 */
const AppRoutes: React.FC<{}> = () => {
  const dispatch = useAppDispatch()
  const roles = useAppSelector(selectUserRoles)
  const token = useAppSelector(selectUserToken)

  const location = useLocation();

  // 页面切换时的进度条
  useEffect(() => {
    NProgress.start();
    return () => {
      NProgress.done();
    };
  }, [location.pathname]);

  // 如果尚未获取用户信息，先 dispatch fetchUserInfo
  useEffect(() => {
    if (!roles || roles.length === 0) {
      dispatch(fetchUserInfo());
    }
  }, [dispatch, roles]);

  // 动态过滤路由
  const filteredAsyncRoutes = filterAsyncRoutes(asyncRoutes, roles)

  // 最终用于渲染的路由数组 = constantRoutes + filteredAsyncRoutes
  let routes: RouteObject[] = [...constantRoutes, ...filteredAsyncRoutes];

  // 如果没有 token，且访问的不是静态路由（如 /login、/404），则重定向到登录页
  if (!token) {
    routes = [
      ...constantRoutes,
      {
        path: '*',
        element: <Navigate to="/login" replace state={{ from: window.location }} />,
      },
    ]
  } else {
    // 如果有 token，但直接访问根路径 /，则重定向到 / （Dashboard）
    routes.push({
      path: '/',
      element: <Navigate to="/" replace />,
    })
  }

  // useRoutes 根据路由数组返回一个元素树
   // 渲染路由
  return useRoutes(routes as any)
};

/**
 * Router 容器：挂载 BrowserRouter 并渲染 AppRoutes
 */
const AppRouter: React.FC<{}> = () => (
  <Router>
    <SuspenseWrapper>
      <AppRoutes />
    </SuspenseWrapper>
  </Router>
);

export default AppRouter;
